package org.newlucene.core.search;

import java.io.IOException;

import org.newlucene.core.index.IndexReader;
import org.newlucene.core.index.Term;
import org.newlucene.core.index.TermPostings;

public class TermSearcher extends IndexSearcher
{
	private Term term;
    private TermPostings termDocs;

    private boolean maxDocReached = false;

    public TermSearcher(IndexReader indexReader, Term term) throws IOException
    {
    	super(indexReader);
    	this.term = term;
        this.termDocs = indexReader.termPositions(term);
        if (this.termDocs == null)
        {
            throw new IOException("termDocs not found");
        }
        
        if (!termDocs.nextDoc())
        {
            termDocs.close();
            maxDocReached = true;
        }
    }
    
    protected void search(HitCollector hc, int end) throws IOException
    {
        while (!maxDocReached)
        {
            if (termDocs.doc() >= end)
            {
                return;
            }

            float score = termDocs.freq() * boost;            
            hc.collect(termDocs.doc(), score); // collect score
            
            // go for next doc
            if (!termDocs.nextDoc())
            {
                termDocs.close();
                maxDocReached = true;
            }
        }
    }
    
    public String explain()
    {
    	StringBuilder sb = new StringBuilder();
    	sb.append(term.field()).append(":").append(term.text());    	
    	if (boost != 1.0f)
    	{
    		sb.append("^").append(boost);
    	}
    	return sb.toString();
    }
}